/**
 * h5 session存储
 */

const storage = window.localStorage

module.exports = {

	$USetCache(key, value) {
		if (!storage || typeof storage.setItem != 'function')
			return false
		if (typeof value == 'object') {
			value = JSON.stringify(value)
		}
		storage.setItem(key, value)
		return addKeyCacheSet(key)
	},

	$UGetCache(key) {
		if (!storage || typeof storage.getItem != 'function')
			return false
		let result = null
		try {
			result = JSON.parse(storage.getItem(key))
		} catch (e) {
			result = storage.getItem(key) || null
		}
		return result
	},

	$URemoveCache: removeItem,

	// 清除所有缓存
	$URemoveCacheAll() {
		for (let key of keyCacheSet()) {
			removeItem(key)
		}
	},
}

function removeItem(key) {
	if (!storage || typeof storage.removeItem != 'function')
		return false
	storage.removeItem(key)
	return rmKeyCacheSet(key)
}

// 添加缓存键
function addKeyCacheSet(key) {
	if (typeof key == 'undefined')
		return false
	let _cacheSet = keyCacheSet()
	_cacheSet.add(key)
	storage.setItem('_cacheSet', JSON.stringify(Array.from(_cacheSet)))
	return true
}

// 删除缓存键
function rmKeyCacheSet(key) {
	if (typeof key == 'undefined')
		return false
	let _cacheSet = keyCacheSet()
	_cacheSet.delete(key)
	storage.setItem('_cacheSet', JSON.stringify(Array.from(_cacheSet)))
	return true
}

// 缓存键列表set
function keyCacheSet() {
	let _cacheSet = null
	try {
		_cacheSet = JSON.parse(storage.getItem('_cacheSet'))
	} catch (e) {
		_cacheSet = []
	}
	return new Set(_cacheSet)
}